package com.hulytu.invasion.component;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.widget.Toast;

import com.hulytu.invasion.Embrace;
import com.hulytu.invasion.plugin.EnhancePlugin;
import com.hulytu.invasion.plugin.MethodParam;

import java.util.Map;

public abstract class BaseEnhancePlugin<T> implements EnhancePlugin<T> {

    private final Map<String, Object> configs = new ArrayMap<>();

    private T host;

    @Override
    public boolean isCompatible() {
        return pluginVersion() >= Embrace.VERSION;
    }

    @Override
    public void onAppInit(Application application) {
        if (handler == null && Embrace.isUiProcess()) {
            handler = new Handler(Looper.getMainLooper());
        }
    }

    @Override
    public void setConfigs(Map<String, ?> configs) {
        if (configs != null) {
            this.configs.putAll(configs);
        }
    }

    @Override
    public Map<String, ?> getConfigs() {
        return configs;
    }

    @Override
    public void init(T host) {
        this.host = host;
    }

    @Override
    public T getHost() {
        return host;
    }

    @Override
    public Object invoke(String method, Object... args) {
        return null;
    }

    @Override
    public void invoke(MethodParam param) {

    }

    public static Handler handler;

    /**
     * 保存的key
     *
     * @param key
     * @return
     */
    protected String storageKey(String key) {
        return pluginName() + "@" + key;
    }

    protected void toast(String s) {
        Context ctx;
        if (TextUtils.isEmpty(s) || handler == null || (ctx = Embrace.app()) == null) return;

        handler.post(new ToastRunnable(ctx, s));
    }

    static class ToastRunnable implements Runnable {

        private final Context ctx;
        private final String s;

        public ToastRunnable(Context ctx, String s) {
            this.ctx = ctx;
            this.s = s;
        }

        @Override
        public void run() {
            Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show();
        }
    }
}
